/*
 * @Author: deng.liu 
 * @Date: 2019-02-19 17:46:26 
 * @Last Modified by: deng.liu
 * @Last Modified time: 2019-02-19 18:00:34
 */
var worker = new Worker('./worker.js');


function Recorder(config) {
    var self = this;
    
    // 获取计算机设备
    navigator.getUserMedia = navigator.getUserMedia 
                            || navigator.webkitGetUserMedia 
                            || navigator.mozGetUserMedia 
                            || navigator.msGetUserMedia;

    // 创建一个音频对象
    window.AudioContext = window.AudioContext || window.webkitAudioContext;
    this.context = new AudioContext();
    this.config = Object.assign({}, {
      bufferLen: 4096, numChannels: 2, mimeType: 'audio/wav'
    })
    this.callbacks = {
        getBuffer: [],
        exportWAV: []
    }
    // 第二个和第三个参数指的是输入和输出都是单声道，2是双声道
    this.recorder = (this.context.createScriptProcessor || this.context.createJavaScriptNode).call(this.context, this.config.bufferLen, this.config.numChannels, this.config.numChannels);
    this.recording = false;

    if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
      navigator.mediaDevices.getUserMedia({audio: true}).then(function(stream){

        self.input = self.context.createMediaStreamSource(stream);


      }).catch(function(err) {
        console.log(err);
      })
    } else {
      navigator.getUserMedia(
        { audio: true }, // 只启用音频
        function(stream) {
          self.input = self.context.createMediaStreamSource(stream);

        },
        function(error) {
          console.log(error);
        }
      )
    }
    worker.postMessage({
        command: 'init',
        config: {
            sampleRate: this.context.sampleRate,
            numChannels: this.config.numChannels
        }
    })

    worker.onmessage = function(e) {
        var cb = self.callbacks[e.data.command].pop();
        if (typeof cb === 'function') {
            console.log(e.data.data);
            cb(e.data.data);
        }
    }
  }

  // 打开录音
  Recorder.prototype.open = function() {
    var self = this;
    this.recorder.onaudioprocess = function(e) {
      if (!self.recording) {
        return;
      }
      var buffer = [];
      for (var i = 0; i < self.config.numChannels; i++) {
        buffer.push(e.inputBuffer.getChannelData(i));
      }

      worker.postMessage({
          command: 'record',
          buffer: buffer
      })
      
    }
    
    this.input.connect(this.recorder);
    this.recorder.connect(this.context.destination);

  }

  // 开始录音
  Recorder.prototype.start = function() {
    this.recording = true;
  }

  // 停止录音
  Recorder.prototype.stop = function() {
    this.recording = false;
  }


  Recorder.prototype.exportWAV = function(cb, mimeType) {
    mimeType = mimeType || this.config.mimeType;
    cb = cb || this.config.callback;
    if (!cb) {
        throw new Error('Callback not set');
    }
    this.callbacks.exportWAV.push(cb);
    worker.postMessage({
        command: 'exportWAV',
        type: mimeType
    })
  }

  Recorder.prototype.getBuffer = function(cb) {
    cb = cb || this.config.callback;
    if (!cb) {
        throw new Error('Callback not set');
    }
    this.callbacks.getBuffer.push(cb);
    worker.postMessage({
        command: 'getBuffer'
    })
  }
